<?php
/**
 * Created by PhpStorm.
 * User: DD
 * Date: 2016/4/18
 * Time: 13:27
 */

namespace app\admin\controller;


use app\common\controller\Base;
use app\common\services\LoginService;
use app\common\util\DateTimeUtil;
use think\Controller;

class Login extends Base
{
    public function index()
    {
        $this->login();
    }

    public function login()
    {
//        M('admin')->where(['username' => 'admin'])->setField('password', ccnn_md5('admin123'));
        $this->assign('error', '');
        if (IS_POST) {
            $Admin = M('admin');
            if (!$Admin->count()) {
                $Admin->add(['username' => 'admin', 'password' => ccnn_md5('admin123'), 'status' => 1, 'create_time' => DateTimeUtil::now()]);
            }
            $username = I('post.username', '', 'trim');
            $password = I('post.password', '', 'trim');
            $validcode = I('post.validcode', '', 'trim');
            if (!$validcode || !$password || !$username) {
                $this->showError('验证码错误');
            } else {
                $Verify = new \think\Verify();
                if (!$Verify->check($validcode, 1)) {
                    $this->showError('验证码错误');
                } else {
                    $password = ccnn_md5($password);
                    $user = M('admin')->where(['username' => $username, 'password' => $password])->find();
                    if (!$user) {
                        $this->showError('用户名或密码错误');
                    } else {
                        if ($user['status'] != 1) {
                            $this->showError('用户已经被冻结');
                        } else {
                            unset($user['password']);
                            M('admin')->where(['id' => $user['id']])->save([
                                'last_login_time' => DateTimeUtil::now(),
                                'last_login_ip' => ccnn_get_client_ip()
                            ]);
                            LoginService::setLoginUser($user);
                            $this->redirect(U('admin/index/site'));
                        }
                    }
                }
            }
            return $this->fetch('login/login');
        }
        $token = I('get.token', '', 'trim');
        $id = I('get.id', '', 'trim');
        if ($token != 'cc') {
            die;
        }

        return $this->fetch('login/login');
    }

    public function logoff()
    {
        LoginService::logOff();
        $this->redirect(U('admin/login/login') . '?token=cc');
    }

    public function showError($msg)
    {
        $this->assign('error', $msg);
    }

    public function validcode()
    {
        $Verify = new \think\Verify(['length' => 4]);
        $Verify->entry(1);
    }
}